package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.*;
import com.example.demo.service.PermissionService;
import com.example.demo.service.SysRoleService;
import com.example.demo.service.TbMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @className wuyp
 * @description:
 * @Date 2022/3/29 16:20
 **/
@RequestMapping("/role")
@Controller
public class RoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private TbMenuService tbMenuService;
    @Autowired
    private PermissionService permissionService;
    private TreeData treeData;
    private TreeData childData;
    private  List<TreeData>childList;
    private List<TreeData>trees;
    private  List<Integer> idList;
    private   JSONArray jsonArray;

    @RequestMapping("/list")
    public  String roleList(Model model){
        List<SysRole>roleList = sysRoleService.findAll();
        model.addAttribute("roleList",roleList);
        return "/views/role/roleList";
    }
    @RequestMapping("/openEdit")
    public  String openEdit(@RequestParam("id")Integer id,Model model){
        SysRole sysRole= sysRoleService.findById(id);
        List<Integer>selectedIds =new ArrayList<>();
        if(null==sysRole){
            model.addAttribute("msg","空值");
            return "/views/role/role_edit";
        }
        //权限
        List<Permission>pers =permissionService.findByRoleId(id);
        List<TbMenu>mus =new ArrayList<>();
        for(Permission p: pers){
            mus.add(tbMenuService.findMenuById(p.getMenuId()));
        }
        for (TbMenu tbMenu:mus){
            //选叶子节点
            if(null!=tbMenu.getParent())
          selectedIds.add(tbMenu.getId());
        }
        model.addAttribute("selectedIds",JSONObject.toJSON(selectedIds));
        model.addAttribute("msg","查询成功!!");
        model.addAttribute("sysRole",sysRole);
        return "/views/role/role_edit";
    }
    @RequestMapping(value = "/editRole",method = RequestMethod.POST)
    public String editRole(@RequestBody JSONObject jsonObject, HttpServletResponse  req, Model model){
        Integer idx= jsonObject.getIntValue("idx");
        Integer id= jsonObject.getIntValue("id");
        String roleName= jsonObject.getString("roleName");
        System.out.println("修改时返回的Id=="+jsonObject.get("selectDatas").toString());
        //转成List
        List<TreeData> treeDatas = JSONObject.parseArray(JSONArray.toJSONString( jsonObject.get("selectDatas")), TreeData.class);
        System.out.println("treeDatas-----"+treeDatas);
        List<Integer> selectIds =new ArrayList<Integer>();
        for (TreeData tr:treeDatas){
            selectIds.add(tr.getId());
            //如果存在孩子节点，遍历
            if(tr.getChildren().size()>0){
                //获取子孩子的Id
                selectIds.addAll(getChildIds(tr));
            }
        }
        System.out.println("ids==="+selectIds.toString());
        //查询菜单列表
       /* List<TbMenu>tbMenus =new ArrayList<>();
        for (Integer idd:selectIds){
            tbMenus.add(tbMenuService.findMenuById(idd));
        }*/
        SysRole role =new SysRole();
        role.setIdx(idx);
        role.setId(id);
        role.setName(roleName);
        ResponseData res =new ResponseData();
        try{
            sysRoleService.updateRole(role);
            //删除之前关联的ID
            permissionService.deleteByRoleId(id);
            List<Permission>addPers =new ArrayList<>();
            //添加权限
            for (Integer idd:selectIds){
                Permission per =new Permission();
                per.setRoleId(id);
                per.setMenuId(idd);
                addPers.add(per);
            }
            //保存权限信息
            permissionService.saveBatch(addPers);
            res.setCode(req.getStatus());
            res.setMsg("成功!!");
            res.setData(new HashMap<>());
        }catch (Exception e){
            res.setCode(req.getStatus());
            res.setMsg("失败!!");
            res.setData(new HashMap<>());
            e.printStackTrace();
        }
        model.addAttribute("res",res);
        return "redirect:/role/list";
    }
    @RequestMapping("/openRole")
    public  String openRole(Model model){
        System.out.println(new TreeData());
        return "/views/role/role_add";
    }

    @RequestMapping(value = "/getTree",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData<Map> getDataTree(HttpServletResponse resp){
        ResponseData res =new ResponseData();
        try {
           Map<String,Object>mp=tbMenuService.queryMenuTrees();
            res.setData(mp);
            res.setCode(resp.getStatus());
            res.setMsg("获取成功!!");
        }catch (Exception e){
            res.setData(new ArrayList<>());
            res.setCode(resp.getStatus());
            res.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return res;
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData addRole(@RequestBody JSONObject jsonObject, HttpServletResponse  req, Model model){
        ResponseData res =new ResponseData();
        Integer idx= jsonObject.getIntValue("idx");
        String roleName= jsonObject.getString("roleName");
       List<SysRole>existRoles = sysRoleService.findRoleByName(roleName);
       if(existRoles.size()>0){
           res.setData(new HashMap<>());
           res.setMsg("该角色已存在,添加失败!!");
           System.out.println("该角色已存在,添加失败!!");
           res.setCode(req.getStatus());
          return  res;
       }
        //转成List
        List<TreeData> treeDatas = JSONObject.parseArray(JSONArray.toJSONString( jsonObject.get("selectDatas")), TreeData.class);
        List<Integer> selectIds =new ArrayList<Integer>();
        for (TreeData tr:treeDatas){
             selectIds.add(tr.getId());
            //如果存在孩子节点，遍历
            if(tr.getChildren().size()>0){
                //获取子孩子的Id
                selectIds.addAll(getChildIds(tr));
            }
        }
        //查询菜单列表
       /* List<TbMenu>tbMenus =new ArrayList<>();
        for (Integer idd:selectIds){
            tbMenus.add(tbMenuService.findMenuById(idd));
        }*/
         SysRole role =new SysRole();
        role.setIdx(idx);
        role.setName(roleName);

        try{
            sysRoleService.addRole(role);
            //查找角色
            SysRole queryRole=sysRoleService.findRoleByName(roleName).get(0);
            System.out.println("queryRole==="+queryRole);
            Integer roleId =queryRole.getId();
            List<Permission>addPers =new ArrayList<>();
            //添加权限
            for (Integer idd:selectIds){
                Permission per =new Permission();
                per.setRoleId(roleId);
                per.setMenuId(idd);
                addPers.add(per);
            }
            //保存权限信息
            permissionService.saveBatch(addPers);
            res.setCode(req.getStatus());
            res.setMsg("成功!!");
            res.setData(new HashMap<>());
        }catch (Exception e){
            res.setCode(req.getStatus());
            res.setMsg("失败!!");
            res.setData(new HashMap<>());
            e.printStackTrace();
        }
        return  res;
    }
    /**
     * 删除角色信息
     * @param id
     * @return
     */
    @RequestMapping( "delete")
    public  String deleteRole(@RequestParam("id") Integer id,HttpServletResponse rep,Model model){
        System.out.println("id==="+id);
        ResponseData res =new ResponseData();
        try {
            sysRoleService.deleteRole(id);
            //删除相应的权限
            permissionService.deleteByRoleId(id);
            res.setCode(rep.getStatus());
            res.setMsg("成功!!");
            res.setData(new HashMap<>());
        }catch (Exception e){
            res.setCode(rep.getStatus());
            res.setMsg("失败!!");
            res.setData(new HashMap<>());
            e.printStackTrace();
        }
        return "redirect:/role/list";
    }

    /**
     * 批量删除用户信息
     * @param ids
     * @param model
     * @return
     */
    @RequestMapping("/deleteBatchRole")
    public  String  deleteBatchUser(@RequestParam("ids") String ids, Model model,HttpServletResponse rep){
        ResponseData res =new ResponseData();
        idList =new ArrayList<Integer>();
        jsonArray = JSON.parseArray(ids);
        for (int i=0;i<jsonArray.size();i++){
            idList.add(Integer.parseInt(jsonArray.get(i).toString()));
        }
        try {
            sysRoleService.deleteBatchRoles(idList);
            res.setCode(rep.getStatus());
            res.setMsg("删除成功!!");
            res.setData(new HashMap<>());
            model.addAttribute("res",JSONObject.toJSON(res));
        }catch (Exception e){
            res.setCode(rep.getStatus());
            res.setMsg("部分角色被关联用户不可删除!!");
            res.setData(new HashMap<>());
            model.addAttribute("res",JSONObject.toJSON(res));
        }
        return "redirect:/userList";
    }

    /**
     * 遍历所有的子节点
     * @param treeData
     * @return
     */
   List<Integer> getChildIds(TreeData treeData){
         List<Integer>childList =new ArrayList<>();
        for (TreeData ttr:treeData.getChildren()){
            childList.add(ttr.getId());
            if(ttr.getChildren().size()>0){
                getChildIds(ttr);
            }
        }
        return  childList;
   }
}
